package com.asen.commons.core.jdbc.builder.mysql;

import com.asen.commons.core.jdbc.builder.SqlBuilder;
import com.asen.commons.core.jdbc.param.ParamStatementSetter;
import com.asen.commons.core.jdbc.param.SqlContext;
import com.asen.commons.core.meta.dao.Condition;
import com.asen.commons.utils.BaseAssert;
import com.asen.commons.utils.StringUtils;

/**
 * 删除
 *
 * @author Gary
 * @version 1.0
 * @date 2018-11-28
 */
public class DeleteBuilder implements SqlBuilder {

    private SqlContext context;

    private String whereSql;

    private boolean buildFlag = false;

    public DeleteBuilder(Class<?> modelType) {
        this.context = new SqlContext(modelType);
    }

    @Override
    public String getSql() {
        BaseAssert.check(buildFlag, "尚未进行SQL构建，不能执行此操作！");

        StringBuilder sb = new StringBuilder("DELETE _t0 FROM `");
        sb.append(context.getMainTable());
        sb.append("` _t0");

        sb.append(context.getJoinSql());

        if (StringUtils.isNotBlank(whereSql)) {
            sb.append(" WHERE ");
            sb.append(whereSql);
        }

        return sb.toString();
    }

    @Override
    public ParamStatementSetter getParams() {
        return context.getParamSetter();
    }

    public void build(Object model, String... whereFields) throws Exception {
        buildFlag = true;
        WhereBuilder whereBuilder = new WhereBuilder(context);
        whereBuilder.build(model, whereFields);
        whereSql = whereBuilder.getSql();
    }

    public void build(Condition condition) throws Exception {
        buildFlag = true;
        WhereBuilder whereBuilder = new WhereBuilder(context);
        whereBuilder.build(condition);
        whereSql = whereBuilder.getSql();
    }

}
